<template>
  <div class="lg-wangeditor" :class="{ 'gl-disabled': disabled }">
    <toolbar v-if="!readonly" :editor="editorRef" :default-config="toolbarConfig" :mode="props.mode" />
    <editor
      style="height: calc(100% - 41px)"
      v-bind="$attrs"
      :default-config="editorConfig"
      :mode="props.mode"
      @on-created="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css';
import { computed, onBeforeUnmount, shallowRef } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { chooseFile, getFileAccessUrl, getToken, message, uploadFile } from '@/soar';
import { baseURL } from '@/config/global';

type InsertFnType = (url: string, alt: string, href: string) => void;

interface Props {
  /**
   * mos
   */
  mode?: 'default';
  /**
   * 占位符
   */
  placeholder?: string;
  /**
   * 只读
   */
  readonly?: boolean;
  /**
   * 禁用
   */
  disabled?: boolean;
  /**
   * 工具栏配置
   */
  toolbarConfig?: any;
  /**
   * 编辑框配置
   */
  editorConfig?: any;
}

const props = defineProps<Props>();

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const editorConfig = computed(() => {
  const { placeholder, readonly, editorConfig } = props;
  return {
    ...editorConfig,
    placeholder,
    readOnly: readonly,
    MENU_CONF: {
      uploadImage: {
        server: `${window.location.origin + baseURL}/general/file/upload`,
        fieldName: 'files',
        headers: {
          token: getToken(),
        },
        // 自定义选择图片
        customBrowseAndUpload(insertFn: any) {
          // 自己选择文件
          chooseFile({
            accept: 'image/*',
            multiple: false,
          }).then((res) => {
            // 自己上传文件，并得到图片 url alt href
            uploadFile(res[0]).then((res) => {
              // 最后插入图片
              insertFn(getFileAccessUrl(res[0].url), '', '');
            });
          });
        },
        // 自定义插入图片
        customInsert(res: any, insertFn: InsertFnType) {
          insertFn(getFileAccessUrl(res.data[0].url), '', '');
        },
      },
      uploadVideo: {
        server: `${window.location.origin + baseURL}/general/file/upload`,
        fieldName: 'files',
        headers: {
          token: getToken(),
        },
        // 自定义选择图片
        customBrowseAndUpload(insertFn: any) {
          // 自己选择文件
          chooseFile({
            accept: 'video/*',
            multiple: false,
          }).then((res) => {
            // 自己上传文件，并得到图片 url alt href
            uploadFile(res[0]).then((res) => {
              // 最后插入图片
              insertFn(getFileAccessUrl(res[0].url), '', '');
            });
          });
        },
        // 自定义插入图片
        customInsert(res: any, insertFn: InsertFnType) {
          insertFn(getFileAccessUrl(res.data[0].url), '', '');
        },
      },
    },
    customAlert: (s: string, t: string) => {
      switch (t) {
        case 'success':
          message.success(s);
          break;
        case 'info':
          message.info(s);
          break;
        case 'warning':
          message.warning(s);
          break;
        case 'error':
          message.error(s);
          break;
        default:
          message.info(s);
          break;
      }
    },
  };
});

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

defineExpose({
  editorRef,
});
</script>
<script lang="ts">
export default {
  name: 'LgWangeditor',
};
</script>

<style lang="less" scoped>
.lg-wangeditor {
  border: 1px solid #ccc;
  border-radius: 4px;
  height: 500px;
  [data-w-e-toolbar] {
    border-bottom: 1px solid #ccc;
  }
  [data-w-e-textarea] {
    overflow-y: hidden;
    height: 100%;
  }
  &.w-e-full-screen-container {
    z-index: 9999;
  }
}
</style>
